package qc.module.platform.mapper;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.module.platform.dto.phone.OfficialPhoneDto;
import qc.module.platform.entity.QcOfficialPhone;

import java.util.List;


@Mapper
public interface QcOfficialPhoneMapper {
    QcOfficialPhoneMapper MAPPER = Mappers.getMapper(QcOfficialPhoneMapper.class);


    @Mapping(target = "flag", ignore = true)
    @Mapping(target = "odr", ignore = true)
    QcOfficialPhone toEntity(OfficialPhoneDto dto);

    @Mapping(target = "flag", source = "flag.index")
    OfficialPhoneDto toDto(QcOfficialPhone qcOfficialPhone);

    List<OfficialPhoneDto> toDtoList(List<QcOfficialPhone> list);


    default QcOfficialPhone OfficialPhoneDtoToEntity(OfficialPhoneDto dto) {
        //DTO转换为Entity
        QcOfficialPhone qcOfficialPhone = QcOfficialPhoneMapper.MAPPER.toEntity(dto);
        //处理标记，非空时进行转换，空值时使用默认
        Integer flag = null;
        if (dto.getFlag() > 0) {
            try {
                flag = dto.getFlag();
            } catch (NumberFormatException exception) {
                //转换错误不处理，使用默认状态
            }
        }

        //判断排序号可以为空或传入的不是数值；后台控制有效值在1~99，输入无效时设置数据库中为100
        if (dto.getOdr() < 1 || dto.getOdr() > 99) {
            qcOfficialPhone.setOdr(100);
        } else {
            try {
                qcOfficialPhone.setOdr(dto.getOdr());
            } catch (NumberFormatException e) {
                qcOfficialPhone.setOdr(100); // 输入无效值设置数据库中为100
            }
        }
        qcOfficialPhone.setFlag(getResourceStatusFlagEnum(flag));

        return qcOfficialPhone;
    }


    static ResourceStatusFlagEnum getResourceStatusFlagEnum(Integer index) {
        if (index != null && index > 0x0) {
            for (ResourceStatusFlagEnum item : ResourceStatusFlagEnum.values()) {
                if (item.getIndex() == index) {//判断序号使用getIndex，判断内容使用getName
                    return item;
                }
            }
        }
        return ResourceStatusFlagEnum.NORMAL;
    }
}
